    <?php
    /**
     * Created by Shijie Liu. 2017/6/18
     * 添加进购物车模块
     */
    include("DB_util.php");


    $book_id = "'" . $_GET["id"] . "'";
    $book_num = $_GET["num"];
    $user_id = $_COOKIE["user_login"];

//    $book_id = 1011;
//    $book_num = 2;
//    $user_id = "13893542486";

   echo add_goods($book_id, $user_id, $book_num);

    function add_goods($book_id, $user_id, $book_num)
    {

        $db = new DB_util();
        if (isset($_COOKIE["user_login"])) {  //先判断是否登陆

            //判断是否已经添加过
            $sql1 = "SELECT num FROM book_cart where (user_id  = $user_id AND book_id = $book_id);";
            $result = $db->queryDB($sql1);
            $num = $result->fetch_row()[0];

            if ($num > 0) {  //有添加记录

                $sql2 = "UPDATE book_cart SET num = ($num+$book_num) where (user_id  = $user_id AND book_id = $book_id);";
                $db->queryDB($sql2);
                $result_code =  1;  // 1-添加成功

            } else {  //无

                $sql3 = "INSERT INTO book_cart VALUES ($user_id,$book_id,$book_num);";
                $result = $db->queryDB($sql3);

                if ($result) {
                    $result_code =  1;  // 1-添加成功
                } else {
                    $result_code =  0;  //0-添加失败
                }
            }
        } else {
            $result_code = 2;  //2-请先登陆
        }
        return $result_code;
    }



